﻿CREATE FUNCTION QIC.TokenDefine(@Name VARCHAR(MAX), @UserTypeID INT, @Precision INT, @Scale INT, @MaxLength INT, @IsOutPut BIT, @IsReadonly BIT)
RETURNS VARCHAR(MAX)
AS
BEGIN

	DECLARE @Retval VARCHAR(MAX)
	DECLARE @TypeName VARCHAR(MAX)
	DECLARE @IsUserDefined BIT
	DECLARE @SchemaId INT

	SELECT @IsUserDefined = is_user_defined, @TypeName = name, @SchemaId = schema_id
	FROM sys.types WHERE user_type_id = @UserTypeID

	SET @Retval = case @Name when '' THEN '' else QIC.FormatArg(@Name) + ' ' end

	IF @IsUserDefined = 1
	BEGIN
		SET @Retval += QUOTENAME(SCHEMA_NAME(@SchemaId)) + '.' +  QUOTENAME(@TypeName)
	END
	ELSE
	BEGIN
		SET @Retval += @TypeName

		SET @Retval +=
			case
				when @TypeName like '%text' or @TypeName like 'image' or @TypeName like 'sql_variant' or @TypeName like 'xml' or @TypeName like 'BIT' or @TypeName like '%INT' or @TypeName like '%date' or @TypeName like 'date%'
					then ''
				when @TypeName = 'float'
					then '(' + convert(VARCHAR(10), ISNULL(@Precision, 18)) + ')'
				when @TypeName= 'numeric' or @TypeName = 'decimal'
					then '(' + convert(VARCHAR(10), ISNULL(@Precision, 18)) + ',' + convert(VARCHAR(10), ISNULL(@Scale, 0)) + ')'
				when (@TypeName like '%char' or @TypeName like '%binary') AND @MaxLength = -1
					then '(MAX)'
				when @MaxLength is not null
					then '(' + convert(VARCHAR(10), @MaxLength) + ')'
				else ''
			end 
	END

	IF @IsOutPut = 1 SET @Retval += ' OUT'
	IF @IsReadonly = 1 SET @Retval += ' READONLY'

	RETURN @Retval

END